package com.wuxi.common.utils;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * 分表工具类
 */
public class ShardingUtil {

    // 月份格式器 yyyyMM
    private static final DateTimeFormatter MONTH_FORMATTER = DateTimeFormatter.ofPattern("yyyyMM");

    /**
     * 根据基础表名和日期获取分表名
     */
    public static String getShardingTableName(String baseTableName, LocalDate date) {
        if (date == null) {
            return baseTableName;
        }
        return baseTableName + "_" + date.format(MONTH_FORMATTER);
    }

    /**
     * 获取当前月分表名
     */
    public static String getCurrentMonthTableName(String baseTableName) {
        return getShardingTableName(baseTableName, LocalDate.now());
    }

    /**
     * 获取下一个月分表名
     */
    public static String getNextMonthTableName(String baseTableName) {
        return getShardingTableName(baseTableName, LocalDate.now().plusMonths(1));
    }

    /**
     * 从分表名中提取基础表名
     */
    public static String extractBaseTableName(String shardingTableName) {
        int lastUnderscoreIndex = shardingTableName.lastIndexOf("_");
        if (lastUnderscoreIndex > 0 && lastUnderscoreIndex == shardingTableName.length() - 6) {
            return shardingTableName.substring(0, lastUnderscoreIndex);
        }
        return shardingTableName;
    }

    /**
     * 检查是否为分表
     */
    public static boolean isShardingTable(String tableName) {
        return tableName.matches(".+_\\d{6}$");
    }
}
